﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using QuickStart.HotKey;
using QuickStart.Properties;

namespace QuickStart.Forms
{
    public partial class MainForm : Form
    {
        const int HOT_KEY_ID = 100;

        public MainForm()
        {
            InitializeComponent();

            this.Icon = Resources.QuickStartIcon;
            this.notifyIcon1.Icon = Resources.QuickStartIcon;

             ShowAsNotifyIcon(true);

        }

        #region Hot Key
        private void HotKeyInit()
        {
            
            HotKeyFilter hotKeyFilter = new HotKeyFilter();
            hotKeyFilter.HotKeyPressed += HotKeyPressed;
            Application.AddMessageFilter(hotKeyFilter);
        }

        private void HotKeyPressed(Object sender, HotKeyEventArgs e)
        {
            OpenRunForm();
        }

        #endregion


        private void MainForm_Load(object sender, EventArgs e)
        {

            MakeGridColumn();
            BindData("Shortcut");

            HotKeyInit();
        }

        public void BindData(string orderField = "")
        {
           
            StartInfo si = StartInfo.GetInstance();

            if(!String.IsNullOrEmpty(orderField)) OrderField=orderField;

            DataView dt = si.ToDataView(OrderField);

            dataGridView1.Rows.Clear();

            foreach (DataRowView item in dt)
            {
                dataGridView1.Rows.Add(item[0], item[1]);
            }
        }

        public void MakeGridColumn()
        {
            DataGridViewTextBoxColumn shortcutColumn = new DataGridViewTextBoxColumn();
            shortcutColumn.HeaderText = "Shortcut";
            shortcutColumn.Width = 100;
            shortcutColumn.ReadOnly = true;
            dataGridView1.Columns.Add(shortcutColumn);

            DataGridViewTextBoxColumn pathColumn = new DataGridViewTextBoxColumn();
            pathColumn.HeaderText = "Path";
            pathColumn.Width = 350;
            pathColumn.ReadOnly = true;
            dataGridView1.Columns.Add(pathColumn);

            DataGridViewButtonColumn editColumn = new DataGridViewButtonColumn();
            editColumn.Text = "Edit";
            editColumn.UseColumnTextForButtonValue = true;
            editColumn.Width = 100;
            dataGridView1.Columns.Add(editColumn);

            DataGridViewButtonColumn delColumn = new DataGridViewButtonColumn();
            delColumn.Text = "Delete";
            delColumn.UseColumnTextForButtonValue = true;
            delColumn.Width = 100;
            dataGridView1.Columns.Add(delColumn);
        }

        private void MainForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
                this.Activate();
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }

        }

        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            Array oFiles = (System.Array)e.Data.GetData(DataFormats.FileDrop);
            string fname = oFiles.GetValue(0).ToString();

            if (File.Exists(fname))
            {
                MatchCollection mc = Regex.Matches(fname, @"(\w+)(\.\w*)?$");

                if (mc.Count > 0)
                {
                    Group g = mc[0].Groups[1];
                    string shortcut = g.Value;
                    OpenProgramAddingForm(shortcut, fname);
                }
            }
        }


        protected override void OnClosed(EventArgs e)
        {
            HotKeyFilter.UnregisterHotKey(this.Handle, HOT_KEY_ID);
            base.OnClosed(e);
        }

        protected override void OnClosing(CancelEventArgs e)
        {         
            ShowAsNotifyIcon(true);

            e.Cancel = true;

            base.OnClosing(e);
        }

        #region Menu Event

        private void miExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void miProgramAdding_Click(object sender, EventArgs e)
        {
            OpenProgramAddingForm("", "");
        }

        private void miRun_Click(object sender, EventArgs e)
        {
            OpenRunForm();
        }

        private void miAbout_Click(object sender, EventArgs e)
        {
            OpenAboutForm();
        }

        private void popMainForm_Click(object sender, EventArgs e)
        {
            ShowAsNotifyIcon(false);            
        }

        private void ShowAsNotifyIcon(bool bNotifyIcon)
        {
            if (bNotifyIcon)
            {
                notifyIcon1.Visible = true;
                //this.WindowState = FormWindowState.Minimized;
                this.Hide();
                this.ShowInTaskbar = false; // this code will cancel the Hotkey
            }
            else
            {
                notifyIcon1.Visible = false;
                this.Visible = true;
                //this.WindowState = FormWindowState.Normal;
                this.ShowInTaskbar = true;
                this.Activate();
            }

            HotKeyFilter.RegisterHotKey(this.Handle, HOT_KEY_ID, (uint)KeyModifiers.None, Keys.F8);
        }
        
        private void popProgramAdding_Click(object sender, EventArgs e)
        {
            OpenProgramAddingForm("", "");
        }  

        private void popRun_Click(object sender, EventArgs e)
        {
            OpenRunForm();
        }

        private void popAbout_Click(object sender, EventArgs e)
        {
            OpenAboutForm();
        }

        private void popExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OpenProgramAddingForm(string shortcut, string path)
        {
            Form frm = new ProgramAdding(shortcut, path, this);
            frm.ShowDialog();
        }

        private void OpenRunForm()
        {
            RunForm frm = RunForm.GetInstance();
            frm.Show();
            frm.Activate();
        }

        private void OpenAboutForm()
        {
            Form frm = new AboutBox();
            frm.ShowDialog();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                StartInfo si = StartInfo.GetInstance();
                string shortcut = (string)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
                string path = (string)dataGridView1.Rows[e.RowIndex].Cells[1].Value;

                switch (e.ColumnIndex)
                {
                    case 2: //"Edit"
                        ProgramAdding frm = new ProgramAdding(shortcut, path, this, true);
                        frm.ShowDialog();
                        break;

                    case 3: //"Delete"


                        DialogResult dr = MessageBox.Show(this, "Are you sure to delete [ " + shortcut + " ]", "Delete shortcut", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);

                        if (dr == DialogResult.Yes)
                        {
                            si.Delete(shortcut);


                            BindData();
                        }
                        break;

                    default:
                        break;

                }
            }
        }

        private void dataGridView1_Sorted(object sender, EventArgs e)
        {
            SortOrder so = dataGridView1.SortOrder;
            OrderField = so.ToString();
            switch (dataGridView1.Columns.IndexOf(dataGridView1.SortedColumn))
            {
                case 0:
                    OrderField = "Shortcut";
                    if (dataGridView1.SortOrder.ToString() == "Descending") OrderField += " desc";
                    break;

                case 1:
                    OrderField = "Path";
                    if (dataGridView1.SortOrder.ToString() == "Descending") OrderField += " desc";
                    break;

                default:
                    break;
            }
        }

        #endregion

        #region Property

        public string OrderField { get; set; }


        #endregion

     

    }
}
